<?php
namespace app\daohang\controller;

use app\common\controller\Front;

class Search extends Front
{

    public function _initialize()
    {
        //请求过滤
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        //继承上级
        parent::_initialize();
        //post请求
        if( $this->request->isPost() ){
            if($keyWord = input('post.searchText/s')){
                $this->redirect(daohangUrlSearch(['searchText'=>$keyWord],$this->site['action']),302);
            }
            $this->redirect(daohangUrlSearch('','index'),302);
        }
        //请求限制
        if( !$this->searchRequest() ){
            $this->error(lang('dh_error_rest'), 'daohang/index/index');
        }
    }
    
    //站内搜索
    public function index()
    {
        //初始数据
        $info = $this->searchInfo();
        //查询数据
        if($info['searchText']){
            $info['list'] = daohangSelect([
                'cache'      => true,
                'status'     => 'normal',
                'controll'   => ['in',['web','mp','mini']],
                'sort'       => $info['sortName'],
                'order'      => $info['sortOrder'],
                'limit'      => $info['pageSize'],
                'page'       => $info['pageNumber'],
                //'search'     => $info['searchText'],
                'where'      => ['info_name'=>['like','%'.$info['searchText'].'%']],
            ]);
        }
        //模板变量
        $this->assign($info);
        //加载模板
        return $this->fetch();
    }
    
    //搜索网址
    public function web()
    {
        //初始数据
        $info = $this->searchInfo();
        //查询数据
        $info['list'] = daohangSelect([
            'cache'      => true,
            'status'     => 'normal',
            'controll'   => ['eq','web'],
            'sort'       => $info['sortName'],
            'order'      => $info['sortOrder'],
            'limit'      => $info['pageSize'],
            'page'       => $info['pageNumber'],
            'whereOr'    => ['info_name'=>['like','%'.$info['searchText'].'%']],
            'meta_query' => [
                [
                    'key'   => ['eq','info_referer'],
                    'value' => ['like','%'.$info['searchText'].'%']
                ],
            ],
        ]);
        //模板变量
        $this->assign($info);
        //加载模板
        return $this->fetch();
    }
    
    //搜索公众号
    public function mp()
    {
        //初始数据
        $info = $this->searchInfo();
        //查询数据
        $info['list'] = daohangSelect([
            'cache'      => true,
            'status'     => 'normal',
            'controll'   => ['eq','mp'],
            'sort'       => $info['sortName'],
            'order'      => $info['sortOrder'],
            'limit'      => $info['pageSize'],
            'page'       => $info['pageNumber'],
            'search'     => $info['searchText'],
        ]);
        //模板变量
        $this->assign($info);
        //加载模板
        return $this->fetch();
    }
    
    //搜索小程序
    public function mini()
    {
        //初始数据
        $info = $this->searchInfo();
        //查询数据
        $info['list'] = daohangSelect([
            'cache'      => true,
            'status'     => 'normal',
            'controll'   => ['eq','mini'],
            'sort'       => $info['sortName'],
            'order'      => $info['sortOrder'],
            'limit'      => $info['pageSize'],
            'page'       => $info['pageNumber'],
            'search'     => $info['searchText'],
        ]);
        //模板变量
        $this->assign($info);
        //加载模板
        return $this->fetch();
    }
    
    public function baidu()
    {
        $this->redirect('https://www.baidu.com/s?wd='.$this->searchText(),302);
    }
    
    public function sogou()
    {
        $this->redirect('https://www.sogou.com/web?query='.$this->searchText(),302);
    }
    
    public function toutiao()
    {
        $this->redirect('https://so.toutiao.com/search?mod=website&keyword='.$this->searchText(),302);
    }
    
    public function bing()
    {
        $this->redirect('https://cn.bing.com/search?q='.$this->searchText(),302);
    }
    
    public function so()
    {
        $this->redirect('https://www.so.com/s?q='.$this->searchText(),302);
    }
    
    //搜索请求是否合法（间隔睦长）
    private function searchRequest()
    {
        //后台验证开关
        $requestCheck = false;
        if( $configMax = intval(config('daohang.request_max')) ){
            $requestCheck = true;
        }
        if( $configInterval = intval(config('daohang.search_interval')) ){
            $requestCheck = true;
        }
        if($requestCheck == false){
            return true;
        }
        //搜索限制白名单
        if( \daicuo\Auth::check('daohang/search/index', $this->site['user']['user_capabilities'], $this->site['user']['user_caps']) ){
            return true;
        }
        //客户端唯一标识 $_SERVER["HTTP_REFERER"]
        $requestClient = md5($this->request->ip().$this->request->header('user-agent'));
        //60秒内最大请求次数
        if($configMax){
            $requestMax = intval(DcCache('request'.$requestClient));
            if($requestMax > $configMax){
                return false;
            }
            DcCache('request'.$requestClient, $requestMax+1, 60);
        }
        //几秒内不得再次搜索
        if($configInterval){
            if( DcCache('search'.$requestClient) ){
                return false;
            }
            DcCache('search'.$requestClient, 1, $configInterval);
        }
        return true;
    }
    
    //通用基本参数
    private function searchInfo()
    {
        //判断是否有关键词
        if( !$this->query['searchText'] && $this->site['action']!='index'){
            $this->error(lang('dh_error_input_keywords'), 'daohang/index/index');
        }
        //基本参数
        $info = [];
        $info['searchText'] = $this->query['searchText'];
        $info['pageSize']   = daohangLimit($this->query['pageSize']);
        $info['pageNumber'] = DcEmpty($this->query['pageNumber'], $this->site['page']);
        $info['sortName']   = 'info_order desc,info_views';
        $info['sortOrder']  = 'desc';
        $info['pagePath']   = daohangUrlSearch(['searchText'=>$info['searchText'],'pageSize'=> $info['pageSize'],'pageNumber'=>'[PAGE]'], $this->site['action']);
        //所有搜索引擎链接
        $info['searchItem'] = [
            'index'   => daohangUrlSearch(['searchText' => $info['searchText']], 'index'),
            'web'     => daohangUrlSearch(['searchText' => $info['searchText']], 'web'),
            'mp'      => daohangUrlSearch(['searchText' => $info['searchText']], 'mp'),
            'mini'    => daohangUrlSearch(['searchText' => $info['searchText']], 'mini'),
            'baidu'   => daohangUrlSearch(['searchText' => $info['searchText']], 'baidu'),
            'sogou'   => daohangUrlSearch(['searchText' => $info['searchText']], 'sogou'),
            'toutiao' => daohangUrlSearch(['searchText' => $info['searchText']], 'toutiao'),
            'bing'    => daohangUrlSearch(['searchText' => $info['searchText']], 'bing'),
            'so'      => daohangUrlSearch(['searchText' => $info['searchText']], 'so'),
        ];
        //处理SEO优化
        $info['seoTitle'] = str_replace('[searchText]', $info['searchText'], daohangSeo(config('daohang.search_title')));
        $info['seoKeywords'] = str_replace('[searchText]', $info['searchText'], daohangSeo(config('daohang.search_keywords')));
        $info['seoDescription'] = str_replace('[searchText]', $info['searchText'], daohangSeo(config('daohang.search_description')));
        //返回普通信息
        return $info;
    }
    
    //获取关键字
    private function searchText()
    {
        return DcEmpty($this->query['searchText'],'呆错导航系统');
    }
}